package cn.taobaoke.restful.controller;

import cn.taobaoke.restful.constant.Constants;
import cn.taobaoke.restful.domain.AgentEntity;
import cn.taobaoke.restful.domain.UserEntity;
import cn.taobaoke.restful.domain.UserGroupRelation;
import cn.taobaoke.restful.domain.WxGroupEntity;
import cn.taobaoke.restful.exception.TBKException;
import cn.taobaoke.restful.interceptor.Auth;
import cn.taobaoke.restful.service.*;
import lombok.NonNull;
import lombok.RequiredArgsConstructor;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;
import java.util.List;

/**
 * GroupController类.
 * +-----------------------------------------------------------------------------------------------+
 * |类名称: GroupController                                                                         |
 * |创建时间: 3/16/17                                                                               |
 * |功能简介:                                                                                       |
 * |参考链接:                                                                                       |
 * +-----------------------------------------------------------------------------------------------+
 * <p>
 * 1. 添加微信组: POST /api/groups
 * 2. 修改微信组: PUT /api/groups/{id}
 * 3. 删除微信组: DELETE /api/groups/{id}  (暂时不提供删除)
 * 4. 根据Key查询微信组: GET /api/groups/{id}
 * 5. 查询微信组列表: GET /api/groups
 * 6. 添加用户到微信组: PUT /api/groups/{groupKey}/users/{userId}
 * 7. 获取微信组用户列表: GET /api/groups/{groupKey}/users
 * 8. 获取代理的微信组列表: GET /api/groups/agents/{agentId}
 * 9. 获取管理员微信组列表: GET /api/groups/admins
 *
 * @author luch
 */
@RestController
@RequestMapping(value = "/{domain}/{domainId}/api/groups")
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
public class WxGroupController extends BaseController {

    /**
     * 查询微信组列表
     *
     * @return
     */
    @Auth(type = { Auth.AuthType.AGENT, Auth.AuthType.ADMIN })
    @GetMapping("")
    public Result queryWxGroupList(@PathVariable Long domainId) {
        logger.debug("GET /{}/api/groups", domainId);

        Long agentId = getLoginAgentId();
        if (agentId != null) { // 代理
            List<WxGroupEntity> wxGroupEntityList = wxGroupService.getWxGroupListForAgent(agentId, domainId);
            return wrapObj(wxGroupEntityList);
        }

        if (getLoginAdmin() != null) { // 管理员
            List<WxGroupEntity> wxGroupEntityList = wxGroupService.getWxGroupListForAdmin(domainId);
            return wrapObj(wxGroupEntityList);
        }

        logger.error("未授权的[GET /{}/api/groups/]访问", domainId);
        throw new TBKException("未授权的[POST /"+ domainId +"/api/groups/]访问");
    }


    /**
     * 在微信组里面添加用户
     *
     * @param id
     * @param userId
     * @return
     */
    @Auth(type = { Auth.AuthType.AGENT, Auth.AuthType.ADMIN })
    @PutMapping("/{id}/users/{userId}")
    public Result addWxGroupUser(@PathVariable Long domainId, @PathVariable Long id, @PathVariable Long userId) {
        logger.debug("PUT /{}/api/groups/{}/users/{}", domainId, id, userId);

        userService.checkUserExistByUserId(userId, domainId);
        String token = request.getHeader(Constants.Token.AGENT_AUTH_TOKEN);
        if (token != null) {
            AgentEntity agentEntity = agentService.getAgentByTokenAndDomainId(token, domainId);
            WxGroupEntity wxGroupEntity = wxGroupService.checkWxGroupExistForAgent(id, agentEntity.getId(), domainId);
            UserGroupRelation relation = new UserGroupRelation();
            relation.setUserId(userId);
            relation.setGroupId(wxGroupEntity.getId());
            relation = userGroupRelationService.addUserToGroup(relation, domainId);
            return wrapObj(relation);
        }

        token = request.getHeader(Constants.Token.ADMIN_AUTH_TOKEN);
        if (token != null) {
            WxGroupEntity wxGroupEntity = wxGroupService.checkWxGroupExistForAdmin(id, domainId);
            UserGroupRelation relation = new UserGroupRelation();
            relation.setUserId(userId);
            relation.setGroupId(wxGroupEntity.getId());
            relation = userGroupRelationService.addUserToGroup(relation, domainId);
            return wrapObj(relation);
        }

        logger.error("未授权的[POST /{}/api/groups/{}/users/{}]访问", domainId, id, userId);
        throw new TBKException("未授权的[POST /"+ domainId +"/api/groups/" + id + "/users/" + userId + "]访问");
    }

    @Auth(type = { Auth.AuthType.AGENT, Auth.AuthType.ADMIN })
    @PostMapping("/pids")
    public Result getPidListForWxGroups(@PathVariable Long domainId, @RequestBody List<String> groupList) {
        logger.debug("查询微信组PID操作：POST /{}/api/robots/pids {}\n", domainId, groupList);

        return wrapObj(wxGroupService.getPidListForWxGroups(groupList, domainId));
    }


    // TODO 一次将一个群的群信息和用户信息都发过来,有则更新,无则创建关联链
    @Auth(type = { Auth.AuthType.AGENT, Auth.AuthType.ADMIN })
    @PutMapping("")
    public Result addGroupUserList(@PathVariable Long domainId, @RequestBody WxGroupEntity groupEntity) {
        logger.debug("PUT /{}/api/groups", domainId);

        wxGroupService.createOrUpdateGroupAndMembers(groupEntity, domainId);
        return wrapVoid();
    }



    @GetMapping("/shortCouponLink")
    public Result getShortCouponLink(@PathVariable String domain, @PathVariable Long domainId, String group) throws IOException {
        Long agentId = wxGroupService.getAgentIdByGroupName(group, domainId);
        if (agentId == null) agentId = -1l;
        String couponUrl = getCouponUrl(domain);
        String more = String.format("%s/d/%s/p/%d/#", couponUrl, domain, agentId);
        String shortLink = innerAPIService.shortLink(more);
        return wrapObj(shortLink);
    }

    private static String DEFAULT_COUPON_URL = "http://yhq.gittis.co";
    private static String C015_CENTER_HOST = "http://wx.pp028.cn";
    private static String C015_COUPON_URL = "http://coupon.pp028.cn";

    private static String getCouponUrl(String domain) {
        if ("c015".equals(domain)) {
            return C015_COUPON_URL;
        }
        return DEFAULT_COUPON_URL;
    }


    // TODO 群控管理机器人
    // 如何给新增的代理: 1) 分配代理群(与发单机器人紧密绑定),以及群裂变操作, 2)创建推广位


    // TODO 下面接口需要修改调整

    /**
     * @param id
     * @return
     */
    @Auth(type = { Auth.AuthType.AGENT, Auth.AuthType.ADMIN })
    @GetMapping("/{id}/users")
    public Result getGroupUsers(@PathVariable Long domainId, @PathVariable Long id) {
        logger.debug("/{}/api/groups/{}/users", domainId, id);

        String token = request.getHeader(Constants.Token.AGENT_AUTH_TOKEN);
        if (token != null) { // 代理
            AgentEntity agentEntity = agentService.getAgentByTokenAndDomainId(token, domainId);
            wxGroupService.checkWxGroupExistForAgent(id, agentEntity.getId(), domainId);
            List<UserEntity> userList = userService.getUsersInGroup(id, domainId);
            return wrapObj(userList);
        }

        token = request.getHeader(Constants.Token.ADMIN_AUTH_TOKEN);
        if (token != null) { // 管理员
            wxGroupService.checkWxGroupExistForAdmin(id, domainId);
            List<UserEntity> userList = userService.getUsersInGroup(id, domainId);
            return wrapObj(userList);
        }

        logger.error("未授权的[POST /{}/api/groups/{}/users]访问", domainId, id);
        throw new TBKException("未授权的[POST /"+ domainId +"/api/groups/" + id + "/users/]访问");
    }

    /**
     * @param agentId
     * @return
     */
    @Auth(type = { Auth.AuthType.AGENT, Auth.AuthType.ADMIN })
    @GetMapping("/agents/{agentId}")
    public Result getGroupListForAgent(@PathVariable Long domainId, @PathVariable Long agentId) {
        logger.debug("GET /{}/api/groups/agents/{}", domainId, agentId);

        List<WxGroupEntity> entities = wxGroupService.getWxGroupListForAgent(agentId, domainId);
        return new Result(entities);
    }

    @Auth(type = Auth.AuthType.ADMIN)
    @GetMapping("/admins")
    public Result getGroupListForAdmin(@PathVariable Long domainId) {
        logger.debug("GET /{}/api/groups/admins", domainId);

        List<WxGroupEntity> entities = wxGroupService.getWxGroupListForAdmin(domainId);
        return new Result(entities);
    }


    private final @NonNull
    WxGroupService wxGroupService;

    private final @NonNull
    AgentService agentService;

    private final @NonNull
    UserService userService;

    private final
    @NonNull
    InnerAPIService innerAPIService;



    private final @NonNull
    UserGroupRelationService userGroupRelationService;

    private static Logger logger = LogManager.getLogger(WxGroupController.class);
}
